import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import { FetchService } from "../../../../core/net/fetch.service";
import * as _ from 'lodash';
import * as moment from 'moment';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-wt-inlet',
    templateUrl: './wt-inlet.component.html',
    styleUrls: ['./wt-inlet.component.scss', '../water-takes-report.component.scss']
})
export class WtInletComponent implements OnInit {
    listData = [];
    tempType = '1';
    contentTitle: string;
    today: Date;
    datePicker: Date = new Date();

    tableData = [];
    dataGroup = {};
    objectKeys = Object.keys;
    modalTableData = [];
    modalDataGroup = {};
    basicOpts: any = {
        title: {
            left: 'center',
            textStyle: {
                color: "#777",
                fontSize: 16
            }
        },
        color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b'],
        // grid: {
        //     top: '10%',
        //     left: '3%',
        //     right: '4%',
        //     bottom: '8%',
        //     containLabel: true
        // },
        tooltip: {
            trigger: "axis"
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['4h', '8h', '12h', '16h', '20h', '24h']
        },
        yAxis: {
            type: "value"
        },
        series: []
    };
    hasFlowChart: boolean = false;
    hasLevelChart: boolean = false;
    levelEchartsIntance: any;
    flowEchartsIntance: any;
    flowOpts: any = {};
    levelOpts: any = {};

    workNumEchartsIntance: any;
    workFlowEchartsIntance: any;
    workNumOpts: any = {};
    workFlowOpts: any = {};
    frId: string;

    modalTitle: string = '干渠进口水位流量历史数据';
    modalShow: boolean = false;
    progressModalShow: boolean = false;
    inletProgressData = [];
    reportFinished = 0;
    reportUnfinished = 0;
    reportPercentage = 0;
    constructor(private fetchService: FetchService,
                private http: HttpClient) {
    }

    ngOnInit() {
        this.fetchService.post<any>('muw/wrsMuwFr/list', {type: "1"}).subscribe(res => {
            this.listData = res;
            this.selectedAreaChanged(this.listData[0].id);
        });
        this.today = new Date();
        this.getInletProgressData();
    }

    selectedAreaChanged(id): void {
        const selectedArea = _.find(this.listData, item => {
            return item.id === id;
        });
        this.contentTitle = selectedArea.name;
        this.tempType = selectedArea.irrType;
        this.frId = id;
        this.getMainContentData(this.today);
    }

    getMainContentData(date): void {
        const time = moment(date).valueOf();
        this.fetchService.post<any>('muw/wrsMuwWfData/list', {frId: this.frId, time: time}).subscribe(res => {
            if (this.tempType === '2') {
                const dataGroup = _.keyBy(res.wrsMuwWfDatas, 'srName');
                const keyArr = this.objectKeys(dataGroup);
                this.dataGroup = this.getIrrigateDataGroup(res.wrsMuwWfDatas);
                this.selectedRow(this.dataGroup[keyArr[0]], keyArr[0]);
            } else {
                this.tableData = res.wrsMuwWfDatas;
                this.selectedRow(this.tableData[0]);
            }
        });
    }

    openDetailModal(): void {
        this.modalShow = true;
        this.queryInfo(this.today);
    }

    getInletProgressData(): void {
        this.fetchService.get<any>('muw/submit/querySubmitWf').subscribe(res => {
            if (res) {
                const group = _.groupBy(res, 'statu');
                this.reportFinished = group['2'] ? group['2'].length : 0;
                this.reportUnfinished = group['1'] ? group['1'].length : 0;
                this.reportPercentage = res.length === 0 ? 0 : Math.round(this.reportFinished / res.length * 100);
                res.forEach(item => {
                    item['status'] = item.statu === 1 ? '未报送' : '已报送';
                    item['hour'] = item.hour && `${item.hour}h`;
                });
                this.inletProgressData = _.sortBy(res, o => {
                    return o.statu;
                });
            }
        });
    }
    openProgressModal(): void {
        this.progressModalShow = true;
    }
    exportFile(): void {
        const param = {
            frId: this.frId ? this.frId : ''
        };
        this.fetchService.export('muw/wrsMuwWfData/export', param).subscribe((res: any) => {
            const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
            const elink = document.createElement('a');

            elink.download = `${this.contentTitle}干渠进水口水位流量表.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }
    print(): void {
    }

    onModalCancel() {
        this.modalShow = false;
    }
    closeProgressModal() {
        this.progressModalShow = false;
    }
    queryInfo(date): void {
        const time = moment(date).valueOf();
        this.fetchService.post<any>('muw/wrsMuwWfData/list', {frId: this.frId, time: time}).subscribe(res => {
            if (this.tempType === '2') {
                this.modalDataGroup = this.getIrrigateDataGroup(res.wrsMuwWfDatas);
            } else {
                this.modalTableData = res.wrsMuwWfDatas;
            }
        });
    }

    selectedRow(data, title?): void {
        console.log(data);
        const start = moment(this.today).subtract(7, "days").valueOf();
        const end = moment(this.today).valueOf();

        if (this.tempType === '2') {
            const params = {
                srId: data[0].srId,
                startDate: start,
                endDate: end
            };
            this.fetchService.post<any>('muw/wrsMuwWfData/historyDataList', params).subscribe(res => {
                res.forEach(item => {
                    item.time = moment(item.date).format("YYYY-MM-DD");
                });
                console.log(res);
                const xAxisArr = res.map(item => {
                    return item.time;
                });
                const legendArr = data.map(item => {
                    return item.trName;
                });
                const seriesWNData = data.map(item => {
                    const seriesData = [];
                    res.forEach(results => {
                        results.wrsMuwWfDatas.forEach(o => {
                            if (o.trName === item.trName) {
                                seriesData.push(parseFloat(o.workNum || '0') + parseFloat(o.workNumS  || '0'));
                            }
                        });
                    });
                    return {
                        name: item.trName,
                        type: 'line',
                        data: seriesData
                    };
                });
                const seriesWFData = data.map(item => {
                    const seriesData = [];
                    res.forEach(results => {
                        results.wrsMuwWfDatas.forEach(o => {
                            if (o.trName === item.trName) {
                                seriesData.push(o.workFlow);
                            }
                        });
                    });
                    return {
                        name: item.trName,
                        type: 'line',
                        data: seriesData
                    };
                });
                const commonOpts = {
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            type: "line",
                            animation: false,
                            label: {
                                backgroundColor: "#505765"
                            }
                        }
                    },
                    legend: {
                        bottom: '4%',
                        data: legendArr
                    },
                    // grid: {
                    //     top: '10%',
                    //     left: '8%',
                    //     right: '8%',
                    //     bottom: '12%',
                    //     containLabel: true
                    // },
                    xAxis: {
                        data: xAxisArr,
                        axisLabel: {
                            interval: 0
                        }
                    },
                    color: ['#1ada6f', '#ffbf44', '#12d0d2', '#0092f1', '#ffdc00', '#f9383b']
                };
                this.workNumOpts = {
                    ...commonOpts, ...{
                        title: {
                            text: `${title}开机数量过程曲线`,
                            left: 'center',
                            textStyle: {
                                color: "#777",
                                fontSize: 16
                            },
                        },
                        yAxis: {
                            name: '开机数量(台)'
                        },
                        series: seriesWNData
                    }
                };
                this.workFlowOpts = {
                    ...commonOpts, ...{
                        title: {
                            text: `${title}开机流量过程曲线`,
                            left: 'center',
                            textStyle: {
                                color: "#777",
                                fontSize: 16
                            },
                        },
                        yAxis: {
                            name: '开机流量(m³/s)'
                        },
                        series: seriesWFData
                    }
                };
                console.log(this.workNumOpts, this.workFlowOpts);
                this.workNumEchartsIntance.setOption(this.workNumOpts, true);
                this.workFlowEchartsIntance.setOption(this.workFlowOpts, true);
            });
        } else {
            this.hasLevelChart = !!data.wl;
            this.hasFlowChart = !!data.flow;

            setTimeout(() => {
                this.resizeChart();
            });
            this.flowOpts = {
                title: {
                    text: `${data.trName}流量过程历时曲线`
                },
                legend: {
                    bottom: 0,
                    data: ['限定流量', '实际流量']
                },
                yAxis: {
                    name: '流量(m³/s)'
                },
                series: [
                    {
                        name: '限定流量',
                        type: 'line',
                        data: [data.flow, data.flow, data.flow, data.flow, data.flow, data.flow]
                    },
                    {
                        name: '实际流量',
                        type: 'line',
                        data: [data.flowFour, data.flowEight, data.flowTwelve, data.flowSixteen, data.flowTwenty, data.flowTwentyFour]
                    }
                ]
            };
            this.levelOpts = {
                title: {
                    text: `${data.trName}水位过程历时曲线`
                },
                yAxis: {
                    name: '水位(m)'
                },
                legend: {
                    bottom: 0,
                    data: ['警戒水位', '实际水位']
                },
                series: [
                    {
                        name: '警戒水位',
                        type: 'line',
                        data: [data.wl, data.wl, data.wl, data.wl, data.wl, data.wl]
                    },
                    {
                        name: '实际水位',
                        type: 'line',
                        data: [data.wlFour, data.wlEight, data.wlTwelve, data.wlSixteen, data.wlTwenty, data.wlTwentyFour]
                    }
                ]
            };
        }

    }

    levelChartInit(ec) {
        this.levelEchartsIntance = ec;
    }
    flowChartInit(ec) {
        this.flowEchartsIntance = ec;
    }

    workNumChartInit(ec) {
        this.workNumEchartsIntance = ec;
    }
    workFlowChartInit(ec) {
        this.workFlowEchartsIntance = ec;
    }

    resizeChart() {
        if (this.levelEchartsIntance) { this.levelEchartsIntance.resize(); }
        if (this.flowEchartsIntance) { this.flowEchartsIntance.resize(); }
    }
    private getIrrigateDataGroup(resData): any {
        const dataGroup = _.keyBy(resData, 'srName');
        const keyArr = this.objectKeys(dataGroup);
        return _.reduce(keyArr, (prev, value) => {
            const arr = [];
            resData.forEach(item => {
                if (item.srName === value) {
                    arr.push(item);
                }
            });
            prev[value] = arr;
            return prev;
        }, {});
    }
}

